<template>
  <div class="app-container">
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span class="card-title">用户管理</span>
      </div>
      
      <div class="filter-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名/姓名/邮箱/手机号"
          class="filter-item search-input"
          clearable
          prefix-icon="el-icon-search"
          @keyup.enter.native="handleSearch"
          @clear="handleSearch"
        />
        <el-select v-model="searchDept" placeholder="选择部门" clearable class="filter-item" @change="handleSearch">
          <el-option
            v-for="item in departments"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button type="primary" icon="el-icon-search" class="filter-item" @click="handleSearch">搜索</el-button>
        
        <div class="action-buttons">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加用户</el-button>
          <el-button type="danger" icon="el-icon-delete" :disabled="selection.length === 0" @click="handleBatchDelete">批量删除</el-button>
          <el-dropdown split-button type="success" @click="handleImportClick" @command="handleImportCommand" style="height: 36px">
            <i class="el-icon-upload"></i> 导入
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="template">下载导入模板</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="warning" icon="el-icon-download" @click="handleExport">导出</el-button>
          <input
            ref="importFileInput"
            type="file"
            accept=".xlsx,.xls"
            style="display: none"
            @change="handleFileChange"
          />
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="paginatedData"
        border
        stripe
        highlight-current-row
        @selection-change="handleSelectionChange"
        class="user-table"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="username" label="用户名" width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tag size="medium">{{ scope.row.username }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" width="120" show-overflow-tooltip />
        <el-table-column prop="department.name" label="部门" width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tag type="info" size="medium" v-if="scope.row.department && scope.row.department.name">{{ scope.row.department.name }}</el-tag>
            <el-tag type="info" size="medium" v-else-if="scope.row.departmentId">{{ getDepartmentName(scope.row.departmentId) }}</el-tag>
            <el-tag type="info" size="medium" v-else>未分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" width="120" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          :current-page.sync="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredTableData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" @close="resetForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择部门" filterable>
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllUsers,
  getUserWithDeptById,
  addUser,
  updateUser,
  deleteUser,
  batchDeleteUsers,
  importUsers,
  getUserImportTemplate,
  exportUsers,
  searchUsers
} from '@/api/user'
import { getAllDepartments } from '@/api/department'
import { formatTime, handleDownload } from '@/utils'

export default {
  name: 'UserList',
  data() {
    return {
      loading: false,
      tableData: [],
      filteredTableData: [],
      selection: [],
      currentPage: 1,
      pageSize: 10,
      searchKeyword: '',
      searchDept: '',
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        username: '',
        realName: '',
        departmentId: '',
        email: '',
        phone: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        departmentId: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      departments: []
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredTableData.slice(start, end)
    }
  },
  created() {
    this.fetchData()
    this.fetchDepartments()
  },
  methods: {
    formatTime,
    getDepartmentName(departmentId) {
      const department = this.departments.find(item => item.id === departmentId)
      return department ? department.name : '未分配'
    },
    async fetchData() {
      this.loading = true
      try {
        const res = await getAllUsers()
        if (res.code === 200) {
          this.tableData = res.data || []
          this.filteredTableData = [...this.tableData]
        }
      } catch (error) {
        console.error('获取用户列表失败', error)
        this.$message.error('获取用户列表失败')
      } finally {
        this.loading = false
      }
    },
    async fetchDepartments() {
      try {
        const res = await getAllDepartments()
        if (res.code === 200) {
          this.departments = res.data || []
        }
      } catch (error) {
        console.error('获取部门列表失败', error)
        this.$message.error('获取部门列表失败')
      }
    },
    async handleSearch() {
      this.loading = true
      try {
        // 构建搜索参数
        const params = {}
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword
        }
        if (this.searchDept) {
          params.departmentId = this.searchDept
        }
        
        // 如果没有搜索条件，使用之前获取的所有数据
        if (!params.keyword && !params.departmentId) {
          this.filteredTableData = [...this.tableData]
          this.currentPage = 1
          return
        }
        
        // 发送搜索请求到后端
        const res = await searchUsers(params)
        if (res.code === 200) {
          this.filteredTableData = res.data || []
        } else {
          this.$message.error(res.message || '搜索失败')
        }
      } catch (error) {
        console.error('搜索用户失败', error)
        this.$message.error('搜索用户失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
        this.currentPage = 1
      }
    },
    handleSelectionChange(selection) {
      this.selection = selection
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleAdd() {
      this.dialogTitle = '添加用户'
      this.form = {
        id: null,
        username: '',
        realName: '',
        departmentId: '',
        email: '',
        phone: ''
      }
      this.dialogVisible = true
    },
    async handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.loading = true
      try {
        const res = await getUserWithDeptById(row.id)
        if (res.code === 200) {
          const user = res.data
          this.form = {
            id: user.id,
            username: user.username,
            realName: user.realName,
            departmentId: user.departmentId,
            email: user.email,
            phone: user.phone
          }
          this.dialogVisible = true
        }
      } catch (error) {
        console.error('获取用户详情失败', error)
        this.$message.error('获取用户详情失败')
      } finally {
        this.loading = false
      }
    },
    async handleDelete(row) {
      this.$confirm('确认删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.loading = true
        try {
          const res = await deleteUser(row.id)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.fetchData()
          }
        } catch (error) {
          console.error('删除用户失败', error)
          this.$message.error('删除用户失败')
        } finally {
          this.loading = false
        }
      }).catch(() => {})
    },
    async handleBatchDelete() {
      if (this.selection.length === 0) {
        this.$message.warning('请选择要删除的用户')
        return
      }
      
      this.$confirm(`确认删除选中的 ${this.selection.length} 个用户?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.loading = true
        try {
          const ids = this.selection.map(item => item.id)
          const res = await batchDeleteUsers(ids)
          if (res.code === 200) {
            this.$message.success('批量删除成功')
            this.fetchData()
          }
        } catch (error) {
          console.error('批量删除用户失败', error)
          this.$message.error('批量删除用户失败')
        } finally {
          this.loading = false
        }
      }).catch(() => {})
    },
    handleImportClick() {
      this.$refs.importFileInput.click();
    },
    
    handleImportCommand(command) {
      if (command === 'template') {
        this.downloadImportTemplate();
      }
    },
    
    async downloadImportTemplate() {
      try {
        const response = await getUserImportTemplate();
        if (!response || !response.data) {
          throw new Error('下载模板失败：响应数据为空');
        }
        this.handleDownloadBlob(response.data, 'user_import_template.xlsx');
        this.$message.success('模板下载成功');
      } catch (error) {
        console.error('下载模板失败:', error);
        this.$message.error('下载模板失败: ' + (error.message || '未知错误'));
      }
    },
    
    handleDownloadBlob(data, fileName) {
      if (!data) {
        console.error('下载失败：数据为空');
        this.$message.error('下载失败：数据为空');
        return;
      }
      
      try {
        const blob = new Blob([data], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = fileName;
        document.body.appendChild(link); // 添加到body确保在所有浏览器中工作
        link.click();
        document.body.removeChild(link); // 清理DOM
        URL.revokeObjectURL(link.href);
      } catch (error) {
        console.error('文件下载处理失败:', error);
        this.$message.error('文件下载处理失败: ' + (error.message || '未知错误'));
      }
    },
    
    handleFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;
      
      const formData = new FormData();
      formData.append('file', file);
      
      this.handleImport({ file: formData });
      
      // Reset the file input to allow re-uploading the same file
      this.$refs.importFileInput.value = '';
    },
    
    async handleImport({ file }) {
      this.loading = true;
      try {
        const response = await importUsers(file);
        if (response.code === 200) {
          this.$message.success(response.message);
          
          // 显示详细导入结果
          const { successCount, failCount, errorMessages } = response.data;
          
          if (errorMessages && errorMessages.length > 0) {
            // 如果有错误信息，显示详细对话框
            this.$alert(
              `<div style="max-height: 300px; overflow-y: auto;">
                <p>成功导入: ${successCount} 条记录</p>
                <p>导入失败: ${failCount} 条记录</p>
                <p>错误详情:</p>
                <ul style="color: #f56c6c; margin: 0; padding-left: 20px;">
                  ${errorMessages.map(msg => `<li>${msg}</li>`).join('')}
                </ul>
              </div>`,
              '导入结果',
              {
                dangerouslyUseHTMLString: true,
                confirmButtonText: '确定'
              }
            );
          }
          
          // 刷新用户列表
          this.fetchData();
        } else {
          this.$message.error(response.message || '导入失败');
        }
      } catch (error) {
        console.error('导入用户出错:', error);
        this.$message.error('导入用户失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    
    async handleExport() {
      this.loading = true;
      try {
        const response = await exportUsers();
        if (!response || !response.data) {
          throw new Error('导出失败：响应数据为空');
        }
        this.handleDownloadBlob(response.data, '用户列表.xlsx');
        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出用户失败', error);
        this.$message.error('导出用户失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.loading = true
          const isEdit = this.form.id !== null
          try {
            const res = isEdit
              ? await updateUser(this.form.id, this.form)
              : await addUser(this.form)
            
            if (res.code === 200) {
              this.$message.success(isEdit ? '更新成功' : '添加成功')
              this.dialogVisible = false
              this.fetchData()
            }
          } catch (error) {
            console.error(isEdit ? '更新用户失败' : '添加用户失败', error)
            this.$message.error(isEdit ? '更新用户失败' : '添加用户失败')
          } finally {
            this.loading = false
          }
        }
      })
    },
    resetForm() {
      this.$refs.form && this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .card-title {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
  }
  
  .filter-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 20px;
    
    .filter-item {
      margin-right: 10px;
      margin-bottom: 10px;
    }
    
    .search-input {
      width: 300px;
    }
    
    .action-buttons {
      margin-left: auto;
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
  }
  
  .user-table {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style> 